package com.jldt.kuaishou.flkuaishou;

import android.app.Activity;
import android.util.Log;

import androidx.annotation.NonNull;


import com.kwai.auth.ILoginListener;
import com.kwai.auth.KwaiAuthAPI;
import com.kwai.auth.common.InternalResponse;
import com.kwai.auth.common.KwaiConstants;
import com.kwai.auth.login.kwailogin.KwaiAuthRequest;
import com.kwai.opensdk.sdk.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class FlutterMethodChannel implements MethodChannel.MethodCallHandler {
    public static final String CHANNEL_NAME = "flutter_kuaishou";
    public static final String INVOKE_NAME = "ANDROID_KuaiShouOpenSDKAuthRequest";
    public static final String TAG = "flutter_kuaishou";

    private MethodChannel channel;
    private Activity activity;


    private static volatile FlutterMethodChannel instance;

    private FlutterMethodChannel() {
    }

    public static FlutterMethodChannel getInstance() {
        if (instance == null) {
            synchronized (FlutterMethodChannel.class) {
                if (instance == null) {
                    instance = new FlutterMethodChannel();
                    Log.e("FlutterMethodChannel...", "[完成]");
                }
            }
        }
        return instance;
    }

    public void init(@NonNull Activity activity, @NonNull BinaryMessenger messenger) {
        this.activity = activity;
        channel = new MethodChannel(messenger, CHANNEL_NAME);
        channel.setMethodCallHandler(this);
        LogUtil.e(TAG, "activity已经创建");

    }

    public void invokeMethod(@NonNull Object arguments) {
        if (channel != null) {
            channel.invokeMethod(INVOKE_NAME, arguments);
        }
    }


    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + android.os.Build.VERSION.RELEASE);
        } else if (call.method.equals("initPlatform")) {
            Log.e(TAG,"initPlatform");
            KwaiAuthAPI.init(activity.getApplication());
            result.success("success");
        } else if (call.method.equals("kuaishouOpenSDKAuthRequest")) {
            Log.e(TAG,"kuaishouOpenSDKAuthRequest");
            final ArrayList<String> platformList = new ArrayList<>(2);
            platformList.add(KwaiConstants.Platform.KWAI_APP);
            platformList.add(KwaiConstants.Platform.NEBULA_APP);
//            platformList.toArray(new String[]{KwaiConstants.Platform.KWAI_APP, KwaiConstants.Platform.NEBULA_APP})

           final  FlutterEventChannel eventChannel = FlutterEventChannel.getInstance();
            KwaiAuthRequest request = new KwaiAuthRequest.Builder()
                    .setState(System.currentTimeMillis() + "")
                    .setAuthMode(KwaiConstants.AuthMode.AUTHORIZE)
                    .setLoginType(KwaiConstants.LoginType.APP)
                    .setPlatformArray(platformList.toArray(new String[platformList.size()])).build();
            final ILoginListener loginListener = new ILoginListener() { // 登录回调的监听
                @Override
                public void onSuccess(@NonNull InternalResponse response) {
                    new Thread(new Runnable() {
                        public void run() {
                            String result = null;
                            int retry = 0;
                            while (null == result && retry < 5) {
                                result = response.getCode();
                                retry++;
                                LogUtil.i(TAG, "retry=" + retry);
                            }
                            LogUtil.e("快手：", response.getCode());
                           // eventChannel.sendEventData(response.getCode());
                        }
                    }).start();
                    Map<String, String> args = new HashMap<>();
                    args.put("code", response.getCode());
                    eventChannel.sendEventData(args);
                }

                @Override
                public void onFailed(String state, int errCode, String errMsg) {
                    LogUtil.e(TAG, "code error is " + errCode + " and msg is " + errMsg);
                    Map<String, String> args = new HashMap<>();
                    args.put("code", String.valueOf(errCode));
                    args.put("msg", errMsg);
                    eventChannel.sendEventData(args);
                }

                @Override
                public void onCancel() {
                    LogUtil.e(TAG, "login is canceled");
                }
            };
            KwaiAuthAPI.getInstance().sendRequest(activity, request, loginListener);
            result.success("success");
        } else {
            result.notImplemented();
        }
    }
}

